<template>
  <div class="user-management">
    <el-card>
      <div class="header">
        <h2>用户管理</h2>
        <el-button type="primary" @click="showAddDialog">添加用户</el-button>
      </div>

      <el-table :data="users" border style="width: 100%">
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="roles" label="角色">
          <template #default="{row}">
            <el-tag v-for="role in row.roles" :key="role.id" style="margin-right: 5px;">
              {{ role.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{row}">
            <el-button size="mini" @click="handleEdit(row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="currentUser" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="currentUser.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="currentUser.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" v-if="!currentUser.id">
          <el-input v-model="currentUser.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="currentUser.roleIds" multiple placeholder="请选择角色">
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.name"
              :value="role.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from '../api'

const users = ref([])
const roles = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加用户')
const currentUser = ref({
  id: null,
  username: '',
  email: '',
  password: '',
  roleIds: []
})

const fetchUsers = async () => {
  try {
    const response = await api.get('/users')
    users.value = response.users
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

const fetchRoles = async () => {
  try {
    const response = await api.get('/roles')
    roles.value = response.roles
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

const showAddDialog = () => {
  dialogTitle.value = '添加用户'
  currentUser.value = {
    id: null,
    username: '',
    email: '',
    password: '',
    roleIds: []
  }
  dialogVisible.value = true
}

const handleEdit = (user) => {
  dialogTitle.value = '编辑用户'
  currentUser.value = {
    id: user.id,
    username: user.username,
    email: user.email,
    password: '',
    roleIds: user.roles.map(role => role.id)
  }
  dialogVisible.value = true
}

const handleDelete = async (user) => {
  try {
    await api.delete(`/users/${user.id}`)
    await fetchUsers()
  } catch (error) {
    console.error('删除用户失败:', error)
  }
}

const handleSubmit = async () => {
  try {
    if (currentUser.value.id) {
      await api.put(`/users/${currentUser.value.id}`, currentUser.value)
    } else {
      await api.post('/users', currentUser.value)
    }
    dialogVisible.value = false
    await fetchUsers()
  } catch (error) {
    console.error('保存用户失败:', error)
  }
}

onMounted(() => {
  fetchUsers()
  fetchRoles()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>
